import { Card, Form, Input, Button, message, Flex } from 'antd';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';

import styles from './index.module.less';
import { loginAPI, regAPI } from '../../api/login';
import { setToken } from '../../utils/tools';

const COUNT = 60;
const Login: React.FC = () => {
  const [count, setCount] = useState(0);

  const navigate = useNavigate();

  //点击事件
  const startHandle = () => {
    if (count !== 0) return;
    setCount(COUNT);
    if (count === 0) {
      // 模拟接口延迟
      setTimeout(() => {
        // 生成四位数的验证码
        const captcha = Math.floor(1000 + Math.random() * 9000).toString();
        // 打印验证码到控制台
        console.log('验证码：', captcha);
      }, 4000);
    }
  };
  //开始倒计时
  useEffect(() => {
    const timer = setTimeout(() => {
      if (count === 0) {
        return;
      }
      setCount(count - 1);
    }, 1000);
    return () => {
      clearTimeout(timer);
    };
  }, [count]);
  return (
    <div className={styles.wrap}>
      <Card
        title='天丰管理系统'
        style={{ width: '500px', height: '250px', margin: '250px auto' }}
      >
        <Form
          labelCol={{ span: 3 }}
          onFinish={async (v) => {
            const res: any = await loginAPI(v);
            // console.log('res', res);
            if (res?.success) {
              //存token
              setToken(res.data);
              navigate('/dashboard');
              message.success(res?.errorMessage);
            } else {
              message.error(res?.errorMessage);
            }
          }}
        >
          <Form.Item
            label='用户名'
            name='userName'
            rules={[{ required: true, message: '用户不能为空' }]}
          >
            <Input placeholder='请输入用户名' />
          </Form.Item>
          <Form.Item
            label='密码'
            name='password'
            rules={[{ required: true, message: '密码不能为空' }]}
          >
            <Input placeholder='请输入密码' />
          </Form.Item>
          <Form.Item style={{ display: 'flex' }}>
            <Button type='primary' htmlType='submit'>
              登录
            </Button>
            <Button
              type='primary'
              onClick={() => {
                navigate('/register');
              }}
            >
              注册
            </Button>
            <Button
              type='primary'
              onClick={startHandle}
              style={{ marginLeft: '200px' }}
            >
              {count == 0 ? '发送验证码' : `${count}`}
            </Button>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default Login;
